import { getPerformanceAdvisorList, performanceAdminScore } from '@/api'
import PeriodSelector from './PeriodSelector'
import MainCard from '@/ui-component/cards/MainCard'
import { gridSpacing, DefaultPagination, PageSizes } from '@/store/constant'
import useColumns from './useColumns'
import { AlertProps } from '@mui/material'
import { GridRowModel, GridRowsProp } from '@mui/x-data-grid-pro'
const index = () => {
  const theme = useTheme()
  const [paginationModel, setPaginationModel] = useState(DefaultPagination)
  const [period, setPeriod] = useState({ start_date: '', end_date: '' })
  const [rows, setRows] = useState<GridRowsProp>([])
  const matches = useMediaQuery(theme.breakpoints.up('lg'))
  const columns = useColumns()
  const reqParams = useMemo(() => {
    return { ...period, page: paginationModel.page + 1, size: paginationModel.pageSize }
  }, [period, paginationModel])
  const {
    data,
    refresh,
    loading: listLoading
  } = useRequest(() => getPerformanceAdvisorList(reqParams), {
    manual: true,
    debounceWait: 500,
    cacheKey: `/performance/period/list_${paginationModel.page}`
  })
  const [snackbar, setSnackbar] = useState<Pick<AlertProps, 'children' | 'severity'> | null>(null)
  const handleClose = () => setSnackbar(null)
  const { runAsync, loading } = useRequest(performanceAdminScore, {
    manual: true,
    onSuccess() {
      refresh()
      setSnackbar({
        severity: 'success',
        children: '管理员评分成功！'
      })
    },
    onError(err) {
      setSnackbar({
        severity: 'error',
        children: err?.message
      })
    }
  })

  useEffect(() => {
    if (data) {
      const list = data.data ?? []
      setRows(list)
    }
  }, [data])

  useEffect(() => {
    if (!isEmpty(pickBy(period))) {
      refresh()
    }
  }, [period, paginationModel])

  const handleUpdateRow = useCallback(
    async (row: GridRowModel) => {
      const score = get(row, 'admin_score')
      const data = {
        advisor_id: get(row, 'advisor_id'),
        score,
        ...period
      }
      if (!isNaN(score)) {
        const updatedRows = rows.map((v) => {
          if (v.advisor_id === get(row, 'advisor_id')) {
            return { ...v, admin_score: score }
          }
          return v
        })
        setRows(updatedRows)
        return await runAsync(data)
      } else {
        return Promise.reject(new Error('score的范围是[0,20]的整数'))
      }
    },
    [period, rows]
  )

  const onProcessRowUpdateError = useCallback((error: Error) => {
    console.log(error)
    setSnackbar({ children: error.message, severity: 'error' })
  }, [])
  return (
    <>
      <MainCard
        title={
          <Grid container spacing={1}>
            <Grid item xs={12} md={4}>
              <Stack spacing={1} direction="row" alignItems="center">
                <PeriodSelector {...{ period, setPeriod }} />
                <LoadingButton
                  loading={listLoading}
                  variant="contained"
                  color="secondary"
                  onClick={() => {
                    refresh()
                  }}
                >
                  Search
                </LoadingButton>
              </Stack>
            </Grid>
          </Grid>
        }
      >
        <Grid container spacing={gridSpacing}>
          <Grid item xs={12} sx={{ minHeight: 500 }}>
            <DataGridPro
              loading={loading}
              rows={rows}
              getRowId={(row) => `${row.advisor_id}`}
              columns={columns}
              editMode="cell"
              pagination
              rowCount={data?.total ?? 20}
              paginationMode="server"
              pageSizeOptions={PageSizes}
              paginationModel={paginationModel}
              onPaginationModelChange={setPaginationModel}
              disableRowSelectionOnClick
              processRowUpdate={(updatedRow, _originalRow) => handleUpdateRow(updatedRow)}
              onProcessRowUpdateError={onProcessRowUpdateError}
              {...(matches && { pinnedColumns: { left: ['name', 'grade', 'rank'], right: ['total_score'] } })}
            />
          </Grid>
        </Grid>
      </MainCard>
      {!!snackbar && (
        <Snackbar autoHideDuration={3000} open onClose={handleClose} anchorOrigin={{ vertical: 'top', horizontal: 'center' }}>
          <Alert onClose={handleClose} sx={{ minWidth: 300 }} {...snackbar}></Alert>
        </Snackbar>
      )}
    </>
  )
}

export default index
